<script setup>
import { ref, onMounted, onUnmounted } from 'vue';
import useUserInfoStore from "@/stores/userInfo.js";
import {ElMessage} from "element-plus";
import {useRouter} from "vue-router";
import dayjs from "dayjs";
import {useInfoStore} from "@/stores/infos.js";
const userInfo = useUserInfoStore()
const messages = useInfoStore()
const readMessage = ref(false)
const router = useRouter()
let eventSource = null;
const formatTimes = (timeString) => {
  return dayjs(timeString).format('YYYY-MM-DD HH:mm:ss')
}
const toPage =async (info)=>{
  messages.removeInfo(info.id);
  await router.push(info.url)
  readMessage.value = false
}
const deleteInfo =async (id)=>{
  messages.removeInfo(id);
  if (messages.info.length===0){
    readMessage.value = false
  }
}

onMounted(() => {
  // 连接 SSE 端点
  const sseUrl = `/api/sse?id=${userInfo.info.id}`;
  eventSource = new EventSource(sseUrl);

  // 监听默认消息事件
  eventSource.onmessage = (event) => {
    let mess = JSON.parse(event.data)
    messages.setInfo(mess);
    // ElMessage.warning(mess.content)
  };

  // 监听自定义事件（对应后端的 name("custom-event")）
  eventSource.addEventListener('custom-event', (event) => {
    messages.setInfo(event.data);
  });

  // 错误处理
  eventSource.onerror = (error) => {
    console.error('SSE 连接错误:', error);
    // 可在此处实现重连逻辑
  };
});

onUnmounted(() => {
  // 组件卸载时关闭连接
  if (eventSource) {
    eventSource.close();
  }
});
</script>

<template>
<div>
  <el-badge v-if="router.currentRoute.value.path!=='/login' && router.currentRoute.value.path!=='/' && router.currentRoute.value.path!=='/syslogin'"
            :value="messages.info.length" class="item"><el-button @click="readMessage=true" :disabled="messages.info.length===0">查看消息</el-button>  </el-badge>
</div>
<!--  <el-dialog-->
<!--      v-model="readMessage"-->
<!--      width="400"-->
<!--      :before-close="handleClose"-->
<!--  >-->
  <el-drawer v-model="readMessage"
             >
    <template #header>
      <h4 style="font-size: 20px">消息列表</h4>
    </template>
    <el-row >
      <el-col :span="18">
        <!-- 消息列表 -->
        <el-list class="message-list">
          <el-list-item
              v-for="(msg, index) in messages.info"
              :key="index"
              class="message-item"
          >
            <template #default>
              <!-- 消息内容区域 -->
              <div class="message-content" style="width: 370px">
                <el-badge style="color: red;margin-top: 1vh" value="×" class="item" @click="deleteInfo(msg.id)"></el-badge>
                <!-- 消息正文 -->
                <el-card shadow="hover" class="message-card">
                  <div class="content-text">{{ msg.content }}</div>

                  <!-- 操作按钮 -->
                  <div class="action-buttons">
                    <el-button
                        type="primary"
                        size="small"
                        @click="toPage(msg)"
                        v-if="msg.url!==null"
                    >
                      <el-icon><link /></el-icon>
                      查看详情
                    </el-button>
                  </div>
                </el-card>
                <!-- 时间显示 -->
                <div class="message-time">
                  <el-icon><clock/></el-icon>
                  {{ formatTimes(msg.times) }}   发送人：{{msg.name}}
                </div>
              </div>
            </template>
          </el-list-item>
        </el-list>
      </el-col>
    </el-row> </el-drawer>
<!--  </el-dialog>-->
</template>

<style scoped lang="scss">
.message-container {
  padding: 20px;
  background-color: #f5f7fa;
  //min-height: 100vh;
}

.message-list {
  background: transparent;
}

.message-time {
  color: darkkhaki;
  font-size: 0.9em;
  margin-bottom: 8px;
  display: flex;
  align-items: center;
  gap: 6px;
}

.message-card {
  border-radius: 8px;
  transition: all 0.3s;
}

.message-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.content-text {
  font-size: 1.1em;
  color: #303133;
  margin-bottom: 12px;
  white-space: pre-wrap;
}

.action-buttons {
  text-align: right;
  margin-top: 12px;
}

.el-icon {
  vertical-align: middle;
  margin-right: 4px;
}
</style>